package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.ExcelFileGenerator
import com.yige.common.ResultUtil
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoLessonStuService
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.ModelMap
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.View
import org.springframework.web.servlet.view.document.AbstractExcelView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * Created by sunhao on 2015/9/17 0017.
 */
@Controller
@RequestMapping("lesson")
class LessonStuController {

    @Autowired
    MongoLessonStuService lessonStuService


    /*************控制器模块************/

    /**
     * 显示课程管理页面
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    def list(Model model){
        def lessonList = lessonStuService.findList() as LinkedList
        model.addAttribute("lessons",lessonList)
        return "lesson/list"
    }

    /**
     * 多条件联合查询课程
     * @param model
     * @param name
     * @param way
     * @return
     */
    @RequestMapping("find")
    def find(Model model, String name, String way){
        def query = new BasicDBObject()
        if(!StringUtils.isEmpty(name)){
            query.append("name",~/${name}/)
        }
        if(!StringUtils.isEmpty(way)){
            query.append("way",~/${way}/)
        }
        def lessonList = lessonStuService.findListByQuery(query) as LinkedList
        model.addAttribute("lessons",lessonList)
        return "lesson/list"
    }

    /**
     * 添加课程
     * @param name
     * @param way
     * @param info
     * @return
     */
    @RequestMapping("addLesson")
    @ResponseBody
    def addLessons(String name, String way, Double price){
        //创建课程信息
        Map<String,Object> lessonInfo = [_id:UUID.randomUUID().toString(),
                                         name:name,
                                         way:way,
                                         price:price]
        DBObject dbObject = ToDBObjectUtil.toDBObject(lessonInfo)
        boolean flag = saveLesson(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除课程
     * @param _ids
     * @return
     */
    @RequestMapping("delLesson")
    @ResponseBody
    def delLesson(@RequestParam('_ids') List<String> _ids){
        //遍历删除课程
        boolean flag = false
        _ids.each {_id->
            flag = lessonStuService.deleteOne(_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 修改课程
     * @param lessonId
     * @param name
     * @param way
     * @param info
     * @return
     */
    @RequestMapping("updateLesson")
    @ResponseBody
    def updateLesson(String _id, String name, String way, Double price){
        //创建课程信息
        Map<String,Object> lessonInfo = [_id:_id,
                                         name:name,
                                         way:way,
                                         price:price]
        DBObject dbObject = ToDBObjectUtil.toDBObject(lessonInfo)
        boolean flag = lessonStuService.updateOne(lessonInfo._id,dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 导出课程表格
     * @param modelMap
     * @return
     */
    @RequestMapping("/export.do")
    def export(ModelMap modelMap){
        View view = new AbstractExcelView() {

            @Override
            protected void buildExcelDocument(Map map,
                                              HSSFWorkbook workbook, HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
                //定义Excel表参数
                String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls";
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + filename) ;

                // 建立 Sheet
                List<String> fieldName = new ArrayList<>()
                fieldName.add("ID")
                fieldName.add("课程名称")
                fieldName.add("教学方式")
                fieldName.add("教学信息")

                List<List<Object>> fieldData = new ArrayList<>()
                List<DBObject> lessonList = lessonService.findList()
                lessonList.each {info->
                    fieldData.add(
                            [info._id,
                             info.name,
                             info.way,
                             info.info]as ArrayList
                    )
                }
                ExcelFileGenerator excel = new ExcelFileGenerator(fieldName,fieldData)
                //开启输出流
                OutputStream outputStream = response.getOutputStream();
                //输出Excel表
                excel.exportExcel(outputStream)
            }
        }
        return new ModelAndView(view,modelMap)
    }


    /*************方法模块***************/

    def saveLesson(DBObject lessonInfo){
        ArgsUtil.checkArgs(lessonInfo)
        DBObject lesson_db = lessonStuService.findOneById(lessonInfo._id)
        if (lesson_db == null) {
            lessonStuService.insertOne(lessonInfo)
            return true
        }else {
            return false
        }
    }


}